package cn.ray_land.flashairtest;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;

public class MainActivity extends AppCompatActivity {

    Button upload;
    Button connect;
    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect = (Button) findViewById(R.id.btn_connect);
        upload = (Button) findViewById(R.id.btn_upload);
        text = (TextView) findViewById(R.id.text);
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new WifiAdmin(getApplicationContext()).openWifi().CreateWifiInfo("flashair_b86b2360d5d0", "12345678", 3);
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(Intent.createChooser(intent, "Select a file"), 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String path = GetPathFromUri4kitkat.getPath(this, uri);
                final File file = new File(path);
                new Thread(){
                    @Override
                    public void run() {
                        FlashAirUploader.upload("file", file, new FlashAirUploader.Callback() {
                            @Override
                            public void onStart() {
                                text.setText("uploading...");
                            }

                            @Override
                            public void onSuccess() {
                                text.setText("upload success");
                            }

                            @Override
                            public void onFailed(String msg) {
                                text.setText("upload failed : " + msg);
                            }
                        });
                    }
                }.start();
            }
        }
    }
}
